/**
 * 格式化日期函数
 * @param {string} dateTemplate - 日期格式模板，默认为 "YYYY-MM-DD hh:mm:ss"
 * @param {Date|string|number} date - 要格式化的日期，可以是 Date 对象、时间戳或可被解析的日期字符串，默认为当前时间
 * @returns {string|null} 格式化后的日期字符串，如果出错则返回 null
 */
export const formatDate = (
  dateTemplate = "YYYY-MM-DD hh:mm:ss",
  date
) => {
  if (!date) {
    date = new Date();
  }
  // 中文星期映射表
  const WeekZhCnMap = {
    0: "日",
    1: "一",
    2: "二",
    3: "三",
    4: "四",
    5: "五",
    6: "六",
  };
  const QuarterZhCnMap = { 1: "一", 2: "二", 3: "三", 4: "四" }

  try {
    // 处理日期输入，转换为Date对象
    let targetDate;
    if (date instanceof Date) {
      targetDate = date;
    } else {
      targetDate = new Date(date);
    }

    // 检查日期有效性
    if (isNaN(targetDate.getTime())) {
      throw new Error("您传入的不是有效的日期格式！");
    }

    // 提取日期组件
    const year = targetDate.getFullYear();
    const month = targetDate.getMonth() + 1;
    const dateNum = targetDate.getDate();
    const hours = targetDate.getHours();
    const minutes = targetDate.getMinutes();
    const seconds = targetDate.getSeconds();
    const quarter = Math.floor(month / 3) + 1;
    const quarterZhCh = QuarterZhCnMap[quarter];
    const week = targetDate.getDay();
    const WeekZhCh = WeekZhCnMap[week];
    const stamp = targetDate.getTime();

    // 定义替换规则映射表
    const replacements = {
      YYYY: year,
      YY: String(year).slice(-2),
      MM: String(month).padStart(2, "0"),
      M: month,
      DD: String(dateNum).padStart(2, "0"),
      D: dateNum,
      hh: String(hours).padStart(2, "0"),
      h: hours,
      mm: String(minutes).padStart(2, "0"),
      m: minutes,
      ss: String(seconds).padStart(2, "0"),
      s: seconds,
      q: quarter, // 新增季度支持
      Q: quarterZhCh,
      w: week,
      W: WeekZhCh,
      t: stamp,
    };
    // 执行替换：根据映射表将模板中的占位符替换为实际值
    return Object.entries(replacements).reduce((str, [key, value]) => {
      return str.replace(new RegExp(key, "g"), value);
    }, dateTemplate);
  } catch (error) {
    console.error("日期格式化错误:", error.message);
    return '日期格式化错误: ' + error.message; // 明确返回null表示格式化失败
  }
};